package szhn.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration
@MapperScan(basePackages = "szhn.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
public class DatasourceConfig {

	@Bean(name = "dataSource", destroyMethod = "close" , initMethod = "init")
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource setDataSource() {
		return DruidDataSourceBuilder.create().build();
		//return DataSourceBuilder.create().build();
	}
	
	@Bean(name = "transactionManager")
	public DataSourceTransactionManager setTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactory setSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mapper/*.xml"));
		factoryBean.setDataSource(dataSource);
		if(factoryBean.getObject() != null) {
			factoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
		}
		return factoryBean.getObject();

	}
	
	@Bean(name = "sqlSessionTemplate")
	public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory)
			throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
	 
}
